package com.cn.handler;

import com.cn.pojo.UserInfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class ClientInboundHandler1 extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(ClientInboundHandler1.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("ClientInboundHandler1 channelActive begin send data");
        /*ByteBuf buf = Unpooled.copiedBuffer("hello server,i am client".getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(buf);*/

        for (int i = 0; i < 100; i++) {
            UserInfo user = new UserInfo(i, "jack" + i, 18, "M", "绿地大道" + i + "号");
            //ctx.writeAndFlush(Unpooled.copiedBuffer(user.toString().getBytes(StandardCharsets.UTF_8)));

            //ctx.writeAndFlush(Unpooled.copiedBuffer(user.toString().concat("\n").getBytes(StandardCharsets.UTF_8)));
            //ctx.writeAndFlush(Unpooled.copiedBuffer(user.toString().concat("$").getBytes(StandardCharsets.UTF_8)));
            ctx.writeAndFlush(Unpooled.copiedBuffer(user.toString().getBytes(StandardCharsets.UTF_8)));
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("ClientInboundHandler1 channelRead");
        ByteBuf buf = (ByteBuf) msg;
        log.info("ClientInboundHandler1: received server data ={}", buf.toString(StandardCharsets.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
